package fr.univ.context.data.handler;

import android.database.Cursor;
import android.provider.BaseColumns;

public class DataBaseHandler < K extends AbstractInfoTable> {
    
	private K abs;
	
	public DataBaseHandler(K abs){
		this.abs = abs;
	}

	 /**
     * Find an entity by it identifier.
     * @param id The identifier.
     * @return Cursor object.
     */
	public Cursor findById(long id){
		
		return abs.getDatabase().query(true, abs.getTableName(), abs.getColumns(), "_id" + "=" + id, 
				null, null, null, null, null);
	}
    
	/**
     * Find all entities of one type.
     * @return Cursor object.
     */
	public Cursor getAll(){	
		
		return getCursor();
	}
    
	/**
     * Persists a new entity in the database or updates an already existing one.
     * @param entity The entity to store or update.
     * @return the row ID of the newly inserted row, or -1 if an error occurred.
     */
    public long insert(EntityBase entity){
       	
    	return abs.getDatabase().insert(abs.getTableName(), null, entity.getContentValues());
    }
    
    /**
     * Persists a new entity in the database or updates an already existing one.
     * @param entity The entity to store or update.
     */
    public void update(EntityBase entity){
    	
    	abs.getDatabase().update(abs.getTableName(), entity.getContentValues(), null, null);
    }
    
    /**
     * Remove an object from persistent storage in the database
     * @param entity The entity to remove.
     * @return the number of rows affected if a whereClause is passed in, 0 otherwise. 
     */
    public int delete(EntityBase entity){
    	
    	return abs.getDatabase().delete(abs.getTableName(), BaseColumns._ID + "=" + entity.getID(), null);    	
    }
    
    private Cursor getCursor(){  	
    	
    	try {
			return abs.getDatabase().query(abs.getTableName(), abs.getColumns(), null, null, null, null, null);
    	} catch (Exception e) {
			return null;
		}
    } 
}
